from functools import reduce


# ############## 基础函数 ##############
def f(x):
    return x * x


def fn(x1, x2):
    return x1 + x2


# 删除偶数，只保留奇数
def is_odd(n):
    return n % 2 == 1


# ############## 高阶函数 ##############
# map()函数
def map_op():
    r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
    print(list(r))  # [1, 4, 9, 16, 25, 36, 49, 64, 81]

    # 将数字转换为字符串
    print(list(map(str, [1, 2, 3])))  # ['1', '2', '3']


# reduce()函数
def reduce_op():
    my_list = [1, 2, 3, 4, 5]
    result = reduce(fn, my_list, 10)
    print(result)  # 25
    print(reduce(lambda x, y: x * y, [1, 2, 3]))  # 一句话解决阶乘函数 6


# filter()函数
def filter_op():
    print(list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])))  # [1, 5, 9, 15]


# sorted()函数
def sorted_op():
    result = sorted([3, -9, -2], key=abs, reverse=True)
    print(result)  # [-9, 3, -2]
    print(sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower))  # ['about', 'bob', 'Credit', 'Zoo']


# ############## 匿名函数lambda ##############
def lambda_op():
    # my_function = lambda a, b: a + b
    # 请按字典中的 value 值进行排序?
    d = {"a": 24, "g": 52, "i": 12, "k": 33}
    result = sorted(d.items(), key=lambda x: x[1])  # [('i', 12), ('a', 24), ('k', 33), ('g', 52)]
    print(result)
    print(reduce(lambda x, y: x * y, [1, 2, 3]))  # 6


# ############## 闭包 ##############
# 定义一个外部函数
def function_out(num1):
    # 定义一个内部函数
    def function_inner(num2):
        # 内部函数使用了外部函数的变量（num1）
        result = num1 + num2
        print("结果是", result)  # 3

    return function_inner


# ############## 装饰器 ##############

if __name__ == '__main__':
    # 创建闭包实例
    # f = function_out(1)
    # 执行闭包
    # f(2)

    map_op()
    reduce_op()
    filter_op()
    sorted_op()
    lambda_op()
    f = function_out(1)
    f(2)
